from flask import Flask, request
from flask import jsonify
from flask_cors import CORS
import sqlite3
from wsgiref.simple_server import make_server

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
sqls = {
    "expert" : "select * from Expert where Eid = '",
    "organizer" : "select * from Organizer where Oid = '",
    "add" : "insert into Questionnaire values(",
    "add2" : "insert into Questionnaire2 values('",
    "result2":"select * from Questionnaire2",
    "add3" : "insert into Questionnaire3 values('",
    "add4" : "insert into Questionnaire4 values('"
}

@app.route('/getUser', methods=['GET', 'POST'])
def home():
    data = request.get_json(silent=True)
    Id = data['id']
    Type = data['type']
    Passwd = data['passwd']
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = ""
    if(Type == 'zuzhizhe'):
        sql = sqls["organizer"]+Id+"'"
    else:
        sql = sqls["expert"] + Id + "'"
    cur.execute(sql)
    res = cur.fetchone()
    con.close()
    if(res==None):
        a = ('889',)
        return jsonify(889)
    elif(res[1]==Passwd):
        res1 = (res[0],res[2])
        return jsonify(res1)
    else:
        a = ('888',)
        return jsonify(888)



@app.route('/addAnswer', methods=['GET', 'POST'])
def homi():
    data = request.get_json(silent=True)
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = sqls["add"]+"'"+data['id']+"',"+"'"+data['q1']+"',"+"'"+data['q2']+"',"+"'"+data['q3']+"')"
    print(sql)
    cur.execute(sql)
    data = cur.fetchone()
    con.commit()
    con.close()
    return jsonify(data)

@app.route('/addAnswer2nd', methods=['GET', 'POST'])
def homii():
    data = request.get_json(silent=True)
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = sqls["add2"]
    for k,v in data.items():
        if(k=="id"):
            sql+=v+"',"
        elif(k=="imcause"):
            sql+=v+");"
        else:
            sql+=v+","
    print(sql)
    cur.execute(sql)
    data = cur.fetchone()
    con.commit()
    con.close()
    return jsonify(data)

@app.route('/addAnswer3rd', methods=['GET', 'POST'])
def homiii():
    data = request.get_json(silent=True)
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = sqls["add3"]
    for k,v in data.items():
        if(k=="id"):
            sql+=v+"',"
        elif(k=="zjgz"):
            sql+=v+");"
        else:
            sql+=v+","
    cur.execute(sql)
    data = cur.fetchone()
    con.commit()
    con.close()
    return jsonify(data)

@app.route('/analyze', methods=['GET', 'POST'])
def analyze2():
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = sqls["result2"]
    cur.execute(sql)
    results = cur.fetchall()
    sums=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    meanpoints= {
        'wages': '',
        'imwages': '',
        'subsidy': '',
        'imsubsidy': '',
        'time': '',
        'imtime': '',
        'frequency': '',
        'imfrequency': '',
        'health': '',
        'imhealth': '',
        'task': '',
        'imtask': '',
        'atmosphere': '',
        'imatmosphere': '',
        'life': '',
        'imlife': '',
        'cause': '',
        'imcause': ''
     }
    for result in results:
        for i in range(18):
            sums[i]+=result[i+1]
    i=0
    for key in meanpoints:
        meanpoints[key] = sums[i]/14
        i+=1
    con.close()
    return jsonify(meanpoints)

@app.route('/addAnswer4th', methods=['GET', 'POST'])
def homiiii():
    data = request.get_json(silent=True)
    con = sqlite3.connect("./questionnaire.db", timeout=10, check_same_thread=False)
    cur = con.cursor()
    sql = sqls["add4"]
    for k,v in data.items():
        if(k=="id"):
            sql+=v+"',"
        elif(k=="zjgz"):
            sql+=v+");"
        else:
            sql+=v+","
    cur.execute(sql)
    data = cur.fetchone()
    con.commit()
    con.close()
    return jsonify(data)

# @app.route('/')
# def index():
#     return app.send_static_file('index.html')
#
#
# @app.route('/<path:fallback>')
# def fallback(fallback):  # Vue Router 的 mode 为 'hash' 时可移除该方法
#     if fallback.startswith('css/') or fallback.startswith('js/') \
#             or fallback.startswith('img/') or fallback == 'favicon.ico':
#         return app.send_static_file(fallback)
#     else:
#         return app.send_static_file('index.html')

# 启动运行
if __name__ == '__main__':
    # server = make_server('127.0.0.1', 5000, app)
    # server.serve_forever()
    app.run()
   # 这样子会直接运行在本地服务器，也即是 localhost:5000
   # app.run(host='your_ip_address') # 这里可通过 host 指定在公网IP上运行

